<!--
* description: 备件清单维护
* author: xiaochengzuan
* createdDate: 2021-3-2
-->

<template>
  <div class="app-container app-container-table" v-loading="tableLoading">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-page-size="30"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="false"
      :dynamic-is-init-table="true"
      :dynamic-api-style="'restful'"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :dynamic-api-style="'restful'"
    />
    <el-dialog
    :title="upLoadRes"
    :visible.sync="dialogVisible"
    width="50%"
    :modal-append-to-body="false"
    >
    <div style="width:100%;height:300px;overflow-y:scroll;">
      <span>{{upLoadMes}}</span>
    </div>    
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="copyText(upLoadMes)">复 制</el-button>
    </span>
  </el-dialog>
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'

import { orgApis } from '@/api/pabasicdataapi'
import { exportExcel } from '@/utils/getTimeString.js'

export default {
  name: 'SparePartsListMaintenance',

  components: {
    OneTableTemplate,
    Edit: () => import('./edit')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // this.$refs['multipleTable'].data = [{bigAreaCode:'1'}]
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {

      editRowData: {},
      // 网格查询API配置对象
      apiConfig: orgApis.sparePartsListMaintenancequery,
      // dialogVisible
      dialogVisible:false,
      // 上传结果标题头
      upLoadRes:null,
      // 上传结果内容
      upLoadMes:null,
      // tableLoading
      tableLoading:false,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          clickEvent: () => this.exportExcel111(),
          text: '导出',
          name: 'export',
          position: 'left'
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          name: 'importTemplate',
          position: 'upload',
          // clickEvent: () => this.handFileListChange(),
          text: '导入'
        },
        {
          compKey: 'comKey11',
          type: 'text',
          size: 'small',
          position: 'upload',
          click: (event) => {
            this.templateDownload()
          }
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '备件编码：',
              codeField: 'partNo',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '备件名称：',
              codeField: 'partName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey10',
              labelName: '备件状态：',
              codeField: 'partStatus',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: orgApis.sparePartsListQuerystateselect
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '维修类型：',
              codeField: 'partRepairType',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: orgApis.sparePartsListQuerycategoryselect
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '销售开关：',
              codeField: 'isSale',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '开放' },
                { statusId: '0', statusText: '关闭' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey6',
              labelName: '订货开关：',
              codeField: 'isOrder',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '开放' },
                { statusId: '0', statusText: '关闭' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: false
            }
          ],

      // 动态生成网格列
      tableCols: [
        {
          prop: 'releaseId',
          label: '主键ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'updateControlId',
          label: '并发控制ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'controlBtn1',
          label: '操作',
          isComponent: true,
          fixed: true,
          comps: [
            {
              compKey: 'propKey1',
              labelName: '修改',
              component: () => import('@/components/org/linkButton'),
              clickEvent: (index) => this.edit(index)
            }
          ]
        },
        {
          prop: 'partNo',
          label: '备件编码',
          hidden: false,
          fixed: true
        },
        {
          prop: 'partName',
          label: '备件名称',
          fixed: true
        },
        {
          prop: 'partNameEn',
          label: '备件英文名称'
        },
        {
          prop: 'partStatusCn',
          label: '备件状态',
          width: '130px'
        },
        {
          prop: 'isSaleCn',
          label: '销售开关'
        },
        {
          prop: 'isOrderCn',
          label: '订货开关'
        },
        {
          prop: 'minOrderAmount',
          label: '最小起订量'
        },
        {
          prop: 'minSaleAmount',
          label: '最小销售数量'
        },
        {
          prop: 'unit',
          label: '备件单位'
        },
        {
          prop: 'orderPeriod',
          label: '订货周期'
        },
        {
          prop: 'arrivalPeriod',
          label: '到货周期'
        },
        {
          prop: 'specifications',
          label: '规格'
        },
        {
          prop: 'origin',
          label: '产地'
        },
        {
          prop: 'isOutsourcingCn',
          label: '允许外购'
        },
        {
          prop: 'bmcCodeCn',
          label: '三电标识'
        },
        {
          prop: 'warrantyPeriod',
          label: '质保期(月)'
        },
        {
          prop: 'is3cCn',
          label: '是否3C件'
        },
        {
          prop: 'c3PieceType',
          label: '3C件类型'
        },
        {
          prop: 'partRepairTypeName',
          label: '维修类型'
        },
        {
          prop: 'carConfigIdList',
          label: '适用车型'
        },
        {
          prop: 'supplierCode',
          label: '供应商编码'
        },
        {
          prop: 'supplierFullName',
          label: '供应商名称'
        },
        {
          prop: 'directDeliveryPieceCn',
          label: '直送件'
        },
        {
          prop: 'vinPieceCn',
          label: 'VIN件'
        },
        {
          prop: 'transportRestrictionsCn',
          label: '运输限制'
        },
        {
          prop: 'abcTypeCn',
          label: 'ABC类'
        },
        {
          prop: 'specialPieceCn',
          label: '特殊件'
        },
        {
          prop: 'keyPieceCn',
          label: '重点件'
        },
        {
          prop: 'isNotReturnCn',
          label: '是否不返件'
        },
        {
          prop: 'replacePieceCn',
          label: '替换件'
        },
        {
          prop: 'length',
          label: '长(MM)'
        },
        {
          prop: 'width',
          label: '宽(MM)'
        },
        {
          prop: 'height',
          label: '高(MM)'
        },
        {
          prop: 'partCubage',
          label: '体积(MM3)'
        },
        {
          prop: 'chargedWeight',
          label: '重量(克)'
        },
        {
          prop: 'baleTypeCn',
          label: '包装类型'
        },
        {
          prop: 'cof',
          label: '摩擦系数'
        },
        {
          prop: 'partAttr',
          label: '备件属性'
        },
        {
          prop: 'isRetrospectCn',
          label: '是否追溯件'
        },
        {
          prop: 'isHomemadeCn',
          label: '追溯件标识'
        },
        {
          prop: 'remark',
          label: '备注'
        }
      ],

      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          partNo: '',
          partName: '',
          partStatus: '',
          partRepairType: '',
          isSale: '',
          isOrder: ''
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      )
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    // 模板下载
    templateDownload() {
      this.$requestAPI({
        method: 'GET',
        variables: { dataType: 'excel' },
        apiUrl: orgApis.downloadTemplate.APIUrl
      }).then((res) => {
        this.$utils.downloadFile(res, 'excel导入模板下载.xlsx')
      })
    },
    handFileListChange(file, fileList) {
        this.handleChange(file)
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType != 'xls' && fileType != 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    beforeRemove(file){},
   async handleChange(param) {     
      if(!param) return 
      this.tableLoading = true 
      const that = this
      const url = orgApis.importListQuery.APIUrl
      let res = await that.$requestUpload(url, param)
      this.tableLoading = false
      if(res.result === '1'){
        const beginIndex = res.msg.indexOf('[')
        this.upLoadRes = res.msg.substring(0,beginIndex)
        this.upLoadMes = res.msg.substring(beginIndex+1,res.msg.length - 1)
        this.dialogVisible = true 
      } else {
        this.$message({
          message:'导入失败', 
          type:'error'
        })
      }
    },
    // 复制到剪切板
    copyText(text){ // text: 要复制的内容， callback: 回调
        var tag = document.createElement('input');
        tag.setAttribute('id', 'cp_hgz_input');
        tag.value = text;
        document.getElementsByTagName('body')[0].appendChild(tag);
        document.getElementById('cp_hgz_input').select();
        document.execCommand('copy');
        document.getElementById('cp_hgz_input').remove();
        this.dialogVisible = false 
        this.$message({
          message:'复制成功'
        })
    },
    // 编辑获取数据
    edit(index) {
      this.editPopupsState = 'edit'
      this.editRowData = this.$utils.deepCopy(
        this.$refs['multipleTable'].list[index]
      )
      this.editPopupsKey = 'opp' + this.$utils.generateId()
      this.editPopupsVisible = true
    },

    // 导出
    exportExcel111() {
      exportExcel(
        this.formField,
        orgApis.sparePartsListMaintenanceexportexcel.APIUrl,
        orgApis.sparePartsListMaintenanceexportexcel.ServiceCode,
        '备件清单维护'
      )
    }
  }
}
</script>
